// pages/workTimeCalendar/index.js
const { appointmentConfigApi } = require("../../utils/api");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 日历数据
    calendarData: [],

    // 工作时间数据
    workTimes: {},

    // 请假数据
    leaveDays: {},

    // 时间选择器相关
    showTimePicker: false,
    selectedDate: "",
    selectedType: "", // 'start' 或 'end'
    currentTime: "",

    // 加载状态
    loading: false,
  },

  onLoad() {
    this.initCalendarData();
    this.loadWorkTimes();
    this.loadLeaveDays();
  },

  onShow() {
    // 页面显示时重新初始化日历数据，确保日期是最新的
    this.initCalendarData();
    // 重新加载请假数据，确保状态同步
    this.loadLeaveDays();
  },

  /**
   * 初始化日历数据
   */
  initCalendarData() {
    // 获取当前本地时间
    const now = new Date();
    const calendarData = [];

    // 生成未来七天（今天、明天、后天...）
    for (let i = 0; i < 7; i++) {
      // 创建新的日期对象，避免修改原始日期
      const date = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() + i
      );

      // 使用本地时间格式化，避免时区问题
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const dateStr = `${year}-${month}-${day}`;

      const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const weekDay = weekDays[date.getDay()];

      let dayLabel;
      if (i === 0) {
        dayLabel = "今天";
      } else if (i === 1) {
        dayLabel = "明天";
      } else {
        dayLabel = "后天";
      }

      calendarData.push({
        id: i + 1,
        date: dateStr,
        dayLabel: dayLabel,
        weekDay: weekDay,
        startTime: "09:30",
        endTime: "22:00",
        isLeave: false,
      });
    }

    this.setData({
      calendarData: calendarData,
    });
  },

  /**
   * 加载工作时间数据
   */
  async loadWorkTimes() {
    try {
      // 直接从数据库加载数据
      await this.loadWorkTimesFromDatabase();
    } catch (error) {
      // 如果数据库加载失败，使用默认数据
      this.setData({
        workTimes: {},
      });
    }
  },

  /**
   * 从数据库加载工作时间数据
   */
  async loadWorkTimesFromDatabase() {
    try {
      const workTimes = {};
      const defaultStartTime = "09:30";
      const defaultEndTime = "22:00";

      // 获取未来7天的工作时间配置
      const today = new Date();
      const datesToCreate = []; // 需要创建默认配置的日期

      for (let i = 0; i < 7; i++) {
        const date = new Date(today.getTime() + i * 24 * 60 * 60 * 1000);
        const dateStr = date.toISOString().split("T")[0];

        try {
          const result = await appointmentConfigApi.getAppointmentConfig(
            dateStr
          );
          if (result.code === 0 && result.data && result.data.id > 0) {
            // 数据库有配置，使用数据库的值
            workTimes[dateStr] = {
              startTime: result.data.start_time,
              endTime: result.data.end_time,
            };
          } else {
            // 数据库没有配置，标记为需要创建默认配置
            workTimes[dateStr] = {
              startTime: defaultStartTime,
              endTime: defaultEndTime,
            };
            datesToCreate.push(dateStr);
          }
        } catch (error) {
          // 如果某天没有配置（404错误），标记为需要创建默认配置
          if (error.status === 404 || error.statusCode === 404) {
            workTimes[dateStr] = {
              startTime: defaultStartTime,
              endTime: defaultEndTime,
            };
            datesToCreate.push(dateStr);
          } else {
            // 其他错误也标记为需要创建默认配置
            workTimes[dateStr] = {
              startTime: defaultStartTime,
              endTime: defaultEndTime,
            };
            datesToCreate.push(dateStr);
          }
        }
      }

      // 如果有需要创建默认配置的日期，先创建它们
      if (datesToCreate.length > 0) {
        await this.createDefaultConfigs(
          datesToCreate,
          defaultStartTime,
          defaultEndTime
        );
      }

      // 更新页面数据
      const calendarData = this.data.calendarData.map((item) => {
        const workTime = workTimes[item.date];
        if (workTime) {
          return {
            ...item,
            startTime: workTime.startTime,
            endTime: workTime.endTime,
          };
        }
        // 如果workTimes中没有该日期，也使用默认值
        return {
          ...item,
          startTime: defaultStartTime,
          endTime: defaultEndTime,
        };
      });

      this.setData({
        workTimes: workTimes,
        calendarData: calendarData,
      });
    } catch (error) {
      // 如果整个加载过程失败，使用默认值
      const defaultStartTime = "09:30";
      const defaultEndTime = "22:00";
      const workTimes = {};
      const today = new Date();

      for (let i = 0; i < 7; i++) {
        const date = new Date(today.getTime() + i * 24 * 60 * 60 * 1000);
        const dateStr = date.toISOString().split("T")[0];
        workTimes[dateStr] = {
          startTime: defaultStartTime,
          endTime: defaultEndTime,
        };
      }

      const calendarData = this.data.calendarData.map((item) => ({
        ...item,
        startTime: defaultStartTime,
        endTime: defaultEndTime,
      }));

      this.setData({
        workTimes: workTimes,
        calendarData: calendarData,
      });
    }
  },

  /**
   * 创建默认配置到数据库
   */
  async createDefaultConfigs(dates, startTime, endTime) {
    try {
      const promises = dates.map(async (dateStr) => {
        const configData = {
          start_time: startTime,
          end_time: endTime,
          interval_minutes: 90, // 默认90分钟间隔
          max_appointments: 0, // 0表示无限制
          status: 1,
        };

        try {
          // 先尝试创建
          const result = await appointmentConfigApi.createAppointmentConfig({
            ...configData,
            date: dateStr, // 添加日期参数
          });
          return result;
        } catch (createError) {
          // 如果创建失败，尝试更新
          try {
            const result = await appointmentConfigApi.updateAppointmentConfig(
              dateStr,
              configData
            );
            return result;
          } catch (updateError) {
            throw updateError;
          }
        }
      });

      await Promise.all(promises);
    } catch (error) {}
  },

  /**
   * 加载请假数据
   */
  async loadLeaveDays() {
    try {
      // 从数据库加载请假状态
      await this.loadLeaveDaysFromDatabase();
    } catch (error) {}
  },

  /**
   * 从数据库加载请假数据
   */
  async loadLeaveDaysFromDatabase() {
    try {
      const leaveDays = {};
      const today = new Date();

      // 获取未来7天的请假状态
      for (let i = 0; i < 7; i++) {
        const date = new Date(today.getTime() + i * 24 * 60 * 60 * 1000);
        const dateStr = date.toISOString().split("T")[0];

        try {
          const result = await appointmentConfigApi.getAppointmentConfig(
            dateStr
          );
          if (result.code === 0 && result.data) {
            leaveDays[dateStr] = result.data.is_leave || false;
          } else {
            leaveDays[dateStr] = false;
          }
        } catch (error) {
          // 如果获取失败，默认为不请假
          leaveDays[dateStr] = false;
        }
      }

      // 更新日历数据中的请假状态
      const calendarData = this.data.calendarData.map((item) => {
        return {
          ...item,
          isLeave: leaveDays[item.date] || false,
        };
      });

      this.setData({
        leaveDays,
        calendarData: calendarData,
      });
    } catch (error) {}
  },

  /**
   * 保存工作时间数据到数据库
   */
  async saveWorkTimes() {
    try {
      // 直接保存到数据库（不再使用本地存储）
      await this.saveWorkTimesToDatabase();
    } catch (error) {}
  },

  /**
   * 保存单个日期的工作时间到数据库
   */
  async saveSingleWorkTimeToDatabase(date) {
    try {
      const workTime = this.data.workTimes[date];
      if (!workTime || !workTime.startTime || !workTime.endTime) {
        return;
      }

      const configData = {
        start_time: workTime.startTime,
        end_time: workTime.endTime,
        interval_minutes: 90, // 默认90分钟间隔
        max_appointments: 0, // 0表示无限制
        status: 1,
      };

      // 尝试更新，如果不存在则创建
      try {
        await appointmentConfigApi.updateAppointmentConfig(date, configData);
      } catch (error) {
        // 如果更新失败，尝试创建
        if (error.message && error.message.includes("不存在")) {
          await appointmentConfigApi.createAppointmentConfig({
            date: date,
            ...configData,
          });
        } else {
          throw error;
        }
      }
    } catch (error) {
      wx.showToast({
        title: "保存失败，请重试",
        icon: "none",
      });
      throw error;
    }
  },

  /**
   * 保存工作时间数据到数据库
   */
  async saveWorkTimesToDatabase() {
    try {
      const workTimes = this.data.workTimes;
      const promises = [];

      // 遍历所有设置的工作时间
      for (const [date, timeConfig] of Object.entries(workTimes)) {
        if (timeConfig && timeConfig.startTime && timeConfig.endTime) {
          const configData = {
            start_time: timeConfig.startTime,
            end_time: timeConfig.endTime,
            interval_minutes: 90, // 默认90分钟间隔
            max_appointments: 0, // 0表示无限制
            status: 1,
          };

          // 尝试更新，如果不存在则创建
          promises.push(
            appointmentConfigApi
              .updateAppointmentConfig(date, configData)
              .then((result) => {
                return result;
              })
              .catch(async (error) => {
                // 如果更新失败，尝试创建
                if (error.message && error.message.includes("不存在")) {
                  const result =
                    await appointmentConfigApi.createAppointmentConfig({
                      date: date,
                      ...configData,
                    });
                  return result;
                }
                throw error;
              })
          );
        }
      }

      // 等待所有API调用完成
      await Promise.all(promises);
    } catch (error) {
      wx.showToast({
        title: "保存失败，请重试",
        icon: "none",
      });
      throw error; // 重新抛出错误，让调用方处理
    }
  },

  /**
   * 保存请假数据
   */
  async saveLeaveDays() {
    try {
      // 保存到数据库而不是本地存储
      await this.saveLeaveDaysToDatabase();
    } catch (error) {}
  },

  /**
   * 保存请假数据到数据库
   */
  async saveLeaveDaysToDatabase() {
    try {
      const leaveDays = this.data.leaveDays;

      // 遍历所有请假状态，保存到数据库
      for (const [date, isLeave] of Object.entries(leaveDays)) {
        if (isLeave !== undefined) {
          try {
            await appointmentConfigApi.toggleLeaveStatus(date, isLeave, "");
          } catch (error) {}
        }
      }
    } catch (error) {
      throw error;
    }
  },

  /**
   * 切换请假状态
   */
  async toggleLeave(e) {
    const { date } = e.currentTarget.dataset;
    const isLeave = this.data.leaveDays[date] || false;
    const action = isLeave ? "取消请假" : "请假";

    // 如果是请假操作，需要特殊处理
    if (!isLeave) {
      wx.showModal({
        title: "确认请假",
        content: `确定要请假${date}吗？\n\n请假后该日期的所有预约将被取消，并通知相关用户。`,
        confirmText: "确认请假",
        confirmColor: "#ff4444",
        success: async (res) => {
          if (res.confirm) {
            await this.handleLeaveAction(date, true);
          }
        },
      });
    } else {
      wx.showModal({
        title: "确认取消请假",
        content: `确定要取消请假${date}吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.handleLeaveAction(date, false);
          }
        },
      });
    }
  },

  /**
   * 处理请假操作
   */
  async handleLeaveAction(date, isLeave) {
    const action = isLeave ? "请假" : "取消请假";

    try {
      wx.showLoading({
        title: `${action}中...`,
      });

      // 如果是请假操作，先取消该日期的所有预约并发送通知
      if (isLeave) {
        await appointmentConfigApi.cancelAppointmentsByDate(
          date,
          "工作时间有变，请到我的预约中查看订单状态"
        );
      }

      // 然后保存请假状态到数据库
      await appointmentConfigApi.toggleLeaveStatus(date, isLeave, "");

      // 更新本地状态
      const leaveDays = { ...this.data.leaveDays };
      leaveDays[date] = isLeave;

      // 更新日历数据
      const calendarData = this.data.calendarData.map((item) => {
        if (item.date === date) {
          return {
            ...item,
            isLeave: isLeave,
          };
        }
        return item;
      });

      this.setData({
        leaveDays,
        calendarData,
      });

      wx.hideLoading();
      wx.showToast({
        title: `${action}成功`,
        icon: "success",
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: `${action}失败，请重试`,
        icon: "none",
      });
    }
  },

  /**
   * 设置工作时间
   */
  setWorkTime(e) {
    const { date, type } = e.currentTarget.dataset;
    const workTime = this.data.workTimes[date] || {
      startTime: "09:30",
      endTime: "22:00",
    };

    // 解析当前时间
    const timeStr = type === "start" ? workTime.startTime : workTime.endTime;

    // 确保 timeStr 是字符串且格式正确
    if (typeof timeStr !== "string" || !timeStr.includes(":")) {
      wx.showToast({
        title: "时间格式错误",
        icon: "none",
      });
      return;
    }

    const [hour, minute] = timeStr.split(":").map(Number);

    // 创建指定日期的日期时间
    const targetDate = new Date(date);
    targetDate.setHours(hour, minute, 0, 0);

    this.setData({
      showTimePicker: true,
      selectedDate: date,
      selectedType: type,
      currentTime: timeStr, // 直接使用时间字符串，而不是时间戳
    });
  },

  /**
   * 时间选择器变化
   */
  onTimeChange(event) {
    const selectedTime = event.detail;
    let timeValue = this.data.currentTime;

    try {
      if (selectedTime && typeof selectedTime === "object") {
        // 处理 van-datetime-picker 的返回值
        if (selectedTime.detail) {
          // 新版本 van-datetime-picker 返回格式
          const values = selectedTime.detail;
          if (values && values.length >= 2) {
            const [hour, minute] = values;
            // 格式化为 HH:MM 字符串
            timeValue = `${hour.toString().padStart(2, "0")}:${minute
              .toString()
              .padStart(2, "0")}`;
          }
        } else if (typeof selectedTime.getValues === "function") {
          // 旧版本处理方式
          const values = selectedTime.getValues();
          if (values && values.length >= 2) {
            const [hour, minute] = values;
            // 格式化为 HH:MM 字符串
            timeValue = `${hour.toString().padStart(2, "0")}:${minute
              .toString()
              .padStart(2, "0")}`;
          }
        } else if (selectedTime.value) {
          timeValue = selectedTime.value;
        }
      }
    } catch (error) {}

    this.setData({
      currentTime: timeValue,
    });
  },

  /**
   * 时间选择器确认
   */
  async onTimePickerConfirm() {
    const { selectedDate, selectedType, currentTime } = this.data;

    if (!selectedDate || !selectedType || !currentTime) {
      wx.showToast({
        title: "请选择时间",
        icon: "none",
      });
      return;
    }

    // currentTime 现在已经是 HH:MM 格式的字符串
    const timeStr = currentTime;

    // 更新工作时间数据
    const workTimes = { ...this.data.workTimes };
    if (!workTimes[selectedDate]) {
      workTimes[selectedDate] = {
        startTime: "09:30",
        endTime: "22:00",
      };
    }

    if (selectedType === "start") {
      workTimes[selectedDate].startTime = timeStr;
    } else {
      workTimes[selectedDate].endTime = timeStr;
    }

    // 更新日历数据
    const calendarData = this.data.calendarData.map((item) => {
      if (item.date === selectedDate) {
        return {
          ...item,
          [selectedType === "start" ? "startTime" : "endTime"]: timeStr,
        };
      }
      return item;
    });

    this.setData({
      workTimes,
      calendarData,
      showTimePicker: false,
      selectedDate: "",
      selectedType: "",
      currentTime: "",
    });

    // 立即保存到数据库
    try {
      await this.saveWorkTimesToDatabase();
      wx.showToast({
        title: "时间设置已保存",
        icon: "success",
      });
    } catch (error) {
      wx.showToast({
        title: "保存失败，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 时间选择器取消
   */
  onTimePickerCancel() {
    this.setData({
      showTimePicker: false,
      selectedDate: "",
      selectedType: "",
      currentTime: "",
    });
  },

  /**
   * 重置单个日期的工作时间
   */
  async resetWorkTime(e) {
    const { date } = e.currentTarget.dataset;
    const defaultStartTime = "09:30";
    const defaultEndTime = "22:00";

    wx.showModal({
      title: "确认重置",
      content: "确定要重置该日期的工作时间为默认时间吗？",
      success: async (res) => {
        if (res.confirm) {
          const workTimes = { ...this.data.workTimes };
          workTimes[date] = {
            startTime: defaultStartTime,
            endTime: defaultEndTime,
          };

          // 同时取消请假状态
          const leaveDays = { ...this.data.leaveDays };
          leaveDays[date] = false;

          // 更新日历数据
          const calendarData = this.data.calendarData.map((item) => {
            if (item.date === date) {
              return {
                ...item,
                startTime: defaultStartTime,
                endTime: defaultEndTime,
                isLeave: false,
              };
            }
            return item;
          });

          this.setData({
            workTimes,
            leaveDays,
            calendarData,
          });

          // 立即保存到数据库（只保存重置的日期）
          try {
            await this.saveSingleWorkTimeToDatabase(date);
            // 只保存选定日期的请假状态
            await appointmentConfigApi.toggleLeaveStatus(date, false, "");
            wx.showToast({
              title: "重置成功",
              icon: "success",
            });
          } catch (error) {
            wx.showToast({
              title: "保存失败，请重试",
              icon: "none",
            });
          }
        }
      },
    });
  },

  /**
   * 重置所有工作时间
   */
  resetAllWorkTimes() {
    wx.showModal({
      title: "确认重置",
      content: "确定要重置所有日期的工作时间为默认时间吗？",
      success: async (res) => {
        if (res.confirm) {
          const workTimes = {};
          const leaveDays = {};
          const defaultStartTime = "09:30";
          const defaultEndTime = "22:00";

          const calendarData = this.data.calendarData.map((item) => ({
            ...item,
            startTime: defaultStartTime,
            endTime: defaultEndTime,
            isLeave: false,
          }));

          // 为未来7天设置默认时间和取消请假
          for (let i = 0; i < 7; i++) {
            const today = new Date();
            const date = new Date(today);
            date.setDate(today.getDate() + i);
            const dateStr = date.toISOString().split("T")[0];
            workTimes[dateStr] = {
              startTime: defaultStartTime,
              endTime: defaultEndTime,
            };
            leaveDays[dateStr] = false;
          }

          // 更新待保存的变更
          const pendingWorkTimeChanges = { ...workTimes };

          this.setData({
            workTimes,
            leaveDays,
            calendarData,
            pendingWorkTimeChanges,
            hasWorkTimeChanges: true,
          });

          // 立即保存到数据库
          try {
            await this.saveWorkTimesToDatabase();
            await this.saveLeaveDays();
            wx.showToast({
              title: "重置成功",
              icon: "success",
            });
          } catch (error) {
            wx.showToast({
              title: "保存失败，请重试",
              icon: "none",
            });
          }
        }
      },
    });
  },

  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    try {
      // 重新加载工作时间数据和请假状态
      await Promise.all([
        this.loadWorkTimesFromDatabase(),
        this.loadLeaveDaysFromDatabase(),
      ]);
    } catch (error) {
    } finally {
      // 停止下拉刷新动画
      setTimeout(() => {
        wx.stopPullDownRefresh();
      }, 1000);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "甲年华美甲美睫 - 工作时间",
      desc: "查看我们的工作时间安排，合理安排您的预约",
      path: "/pages/workTimeCalendar/index",
      imageUrl: "/images/share-worktime.jpg",
    };
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: "甲年华美甲美睫 - 工作时间",
      query: "",
      imageUrl: "/images/share-worktime.jpg",
    };
  },
});
